﻿using System.Linq;
using Fonour.Application.UserApp;
using Fonour.MVC.Models;
using Fonour.Test;
using Fonour.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Fonour.MVC.Controllers
{
    public class LoginController : Controller
    {
        private readonly IUserAppService _userAppService;
        private readonly ILogger _log;
        public LoginController(IUserAppService userAppService, ILogger<LoginController> log)
        {
            this._log = log;
            _userAppService = userAppService;
        }

        [HttpGet]
        public IActionResult Index()
        {
            // var user = _userAppService.CheckUser("admin", "123456");
            ViewBag.ErrorInfo = null;
            return View();
        }

        [HttpPost]
        public IActionResult Index(LoginModel model)
        {

            if (ModelState.IsValid)
            {
                var user = _userAppService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
                
                    _log.LogInformation("hello Test2 被创建");

                    return RedirectToAction("Index", "Home");
                }

                ViewBag.ErrorInfo = "用户名或密码错误";

                return View();
            }

            ViewBag.ErrorInfo = ModelState.Values.First()?.Errors?.FirstOrDefault()?.ErrorMessage;

            return View(model);
        }
    }
}